package com.itheima.health.controller.mobile;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.common.RedisMessageConstant;
import com.itheima.health.dto.SmsLoginParam;
import com.itheima.health.result.Result;
import com.itheima.health.service.SendSmsService;
import com.itheima.health.util.AliSmsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.Map;


@RestController
@RequestMapping("/mobile")
@Slf4j
@Api(tags = "用户端的-相关接口")
public class MobileController {

    @Autowired
    private SendSmsService sendSmsService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获得验证码
     * @param type
     * @param telephone
     * @return
     */
    @PostMapping("/validateCode/send")
    @ApiOperation("获得验证码")
    public Result send(String type, String telephone){
        AliSmsUtil aliSmsUtil = new AliSmsUtil();
        Map map = (Map) redisTemplate.opsForValue().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        Boolean flag = null;
        if (map == null) {
            flag = sendSmsService.sendMessage(type, telephone);
            if(flag){
                return new Result(true,MessageConst.SEND_VALIDATECODE_SUCCESS);
            }
            return new Result(false,MessageConst.SEND_VALIDATECODE_FAIL);
        }
        // 把redis中缓冲的验证码在重新发送
        String code =(String) map.get(RedisConst.VALIDATE_CODE_PREFIX);
        aliSmsUtil.sendMess(telephone,code);
//        validateCodeOrderSetting(telephone);
        return new Result(true,MessageConst.SEND_VALIDATECODE_SUCCESS);
    }

    /*private void validateCodeOrderSetting(String telephone) {
        AliSmsUtil aliSmsUtil = new AliSmsUtil();
        Map map = (Map) redisTemplate.opsForValue().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        String code =(String) map.get(RedisConst.VALIDATE_CODE_PREFIX);
        //获取key1的剩余时间的时间戳
        Long expire = redisTemplate.getExpire(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //最后一个参数可以选秒、毫秒（TimeUnit.MILLISECONDS），Redis最多只能返回毫秒级别的key的剩余过期时间
        redisTemplate.expire(telephone + RedisMessageConstant.SENDTYPE_LOGIN, Duration.ofMillis(expire));
        aliSmsUtil.sendMess(telephone,code);
    }*/

    /**
     * 用户端登录
     * @param smsLoginParam
     * @return
     */
    @PostMapping("/login/smsLogin")
    @ApiOperation("用户端登录")
    public Result login(@RequestBody SmsLoginParam smsLoginParam){
        Boolean  flag = sendSmsService.findByKey(smsLoginParam);
        if(flag){
            return new Result(true,MessageConst.LOGIN_SUCCESS);
        }
        return new Result(false,MessageConst.LOGIN_FAIL);
    }

}
